package com.fj.netty.rpc.client;

import com.fj.netty.rpc.api.HelloService;
import com.fj.netty.rpc.client.handler.RpcResponseMessageHandler;
import com.fj.netty.rpc.message.RpcRequestMessage;
import com.fj.netty.rpc.protocol.RpcMessageCodec;
import com.fj.netty.rpc.protocol.RpcMessageLengthFieldDecoder;
import com.fj.netty.rpc.protocol.SequenceIdUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;

/**
 * @author fj
 * @date 2024/1/17 17:16
 */
@Slf4j
public class RpcClientManager {

    public static void main(String[] args) {
        HelloService service = RpcClientManager.getService(HelloService.class);
        try{
            System.out.println(service.sayHello("xpf"));
//            System.out.println(service.sayHello("abc"));
//            System.out.println(service.sayHello("123"));
        }catch (Exception e){
            log.error("RPC调用异常",e);
        }
    }

    public static <T> T getService(Class<T> clz) {
        return (T) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader()
                , new Class<?>[]{clz}
                , (proxy, method, args) -> {
                    Channel channel = RpcClientManager.getChannel();
                    RpcRequestMessage message = new RpcRequestMessage();
                    message.setInterfaceName(clz.getName());
                    message.setMethodName(method.getName());
                    message.setReturnType(method.getReturnType());
                    message.setParamTypes(method.getParameterTypes());
                    message.setParamObjects(args);
                    message.setSequenceId(SequenceIdUtil.getSequenceId());
                    channel.writeAndFlush(message);
                    //创建promise对象，指定promise异步接收结果的线程池
                    DefaultPromise<Object> promise = new DefaultPromise<>(channel.eventLoop());
                    RpcResponseMessageHandler.PROMISE_MAP.put(message.getSequenceId(), promise);
                    promise.await();//阻塞等待结果
                    if (promise.isSuccess()){
                        return promise.getNow();
                    }else{
                        throw promise.cause();
                    }
                });
    }

    private static Channel channel;

    private RpcClientManager(){

    }

    public static Channel getChannel(){
        if (channel == null){
            synchronized (RpcClientManager.class){
                if (channel == null){
                    initChannel();
                }
            }
        }
        return channel;
    }

    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new RpcMessageLengthFieldDecoder());
                        ch.pipeline().addLast(new RpcMessageCodec());
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new RpcResponseMessageHandler());
                    }
                });
        try {
            channel = bootstrap.connect("127.0.0.1", 6789).sync().channel();
            channel.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    group.shutdownGracefully();
                }
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
